package room_event

import (
	"errors"
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/cache"
	chat2 "longmen/server/internal/rpc/tencentim/chat"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	pb "longmen/server/pkg/protobuf"
	"strconv"

	"github.com/spf113/cast"
)

// 新的匿名用户 SenderUid
var anonymousNameChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZ0123456789"

func GetUser(req *pb.CallbackReq) (*chat2.ClientUser, error) {
	var user *chat2.ClientUser
	formUserId, _ := strconv.Atoi(req.From_Account)
	user = chat2.GetClientUser(formUserId)
	if user == nil || len(user.ClientName) == 0 || user.Role == 0 {
		//global.Log.Debugf("NoCache User%v", req)
		return nil, errors.New("用户信息读取出错")
	}
	return user, nil
}

func AvChatC2CHandler(req *pb.CallbackReq, m *messages2.IncomingMessage, b []byte) (ret *pb.CallbackResp, err error) {
	//global.Log.Debugf("single:%v", req)
	user, err := GetUser(req)
	if err != nil {
		iHeader := 0
		if len(req.From_Account) >= 10 {
			iHeader = len(req.From_Account) - 9
		} else {
			cache.SetClientBeforeLogin(req)
			user, err = GetUser(req)
		}
		if err != nil {
			user = &chat2.ClientUser{
				Platform:   0,
				UserId:     0,
				RoomId:     m.GroupId,
				Token:      "",
				ClientName: global.Lang.T("anonymous") + req.From_Account[iHeader:len(req.From_Account)], //random.String(5, anonymousNameChars),
				Avatar:     "",
				Level:      0,
				Vip:        0,
				UUID:       "",
				Props:      nil,
				Anonymouse: true,
				Role:       0,
				Permit:     0,
			}
		}
	}
	user.UserId = cast.ToInt(req.From_Account)
	user.RoomId = m.GroupId
	user.OptPlatform = req.GetOptPlatform()
	if user.IP == "" {
		user.IP = req.ClientIP
	}
	if user.Platform == 0 {
		user.Platform = utils.PlatformTrans(req.OptPlatform)
	}
	if user.UserId == m.GroupId {
		user.Role = 2
	}
	user.SourceKey = m.SourceKey // 加上渠道信息

	switch *m.Type {
	case messages2.FirstMessageType: // 游客进入房间
		return handlingFirst(req, user)
	case messages2.LoginMessageType: // 登录消息
		return handlingLogin(req, user)
	case messages2.LogoutMessageType:
		return handlingLogout(user)
	case messages2.MatchLiveMessageType: // 比分 + 技术统计
		return handlerMatch(m.GroupId)
	case messages2.TextLiveMessageType: // 文字直播（30条一次）
		return handlingTextLive(m.GroupId)
	case messages2.TextLiveMessagePbType: //返回pb格式文字直播
		return handlingTextLivePb(m.GroupId)
	case messages2.LineupLive1MessageType: // 阵容分段 1
		return handlingLineupLive1(m.GroupId)
	case messages2.LineupLive2MessageType: // 阵容分段 2
		return handlingLineupLive2(m.GroupId)
	case messages2.LineupLive3MessageType: // 阵容分段 3
		return handlingLineupLive3(m.GroupId)
	case messages2.IndexLiveMessageType: // 指数
		return handlingIndexLive(m.GroupId)
	case messages2.BanUserMessageType: // 禁言用户
		return handlingBanUserMessage(user, b), nil
	case messages2.UnbanUserMessageType: // 解除禁言
		return handlingUnbanUserMessage(user, b), nil
	case messages2.GiftFeedMessageType: // 礼物订阅
		return handlingGiftFeedMessage(user, m.GroupId, b)
	case messages2.ClearMessageType: // 屏蔽消息
		return handlingClearMessage(user, b)
	case messages2.PingMessageType: // 心跳消息
		return handlingPingMessage(user, req.ClientIP, b)
	case messages2.ImmeGiftMessageType: // 礼物消息
		return handlingImmeGiftMessage(user, b)
	case messages2.BanSelfMsgType: // 用户触发风控被禁言
		return handlingBanSelfMessage(user, b)
	case messages2.RoomBannedStatusType: // 获取禁言的原因
		return handlingBannedStatusMessage(user, b)
	case messages2.PrivateMessageType: // 私聊信息处理
		return handlingPrivateMessage(user, req.From_Account, b)
	case messages2.PrivateHistoryType: // 获取私聊历史消息
		return handlingPrivateHistory(user, b)
	case messages2.RoomQuizPromptMessageType: // 查询开奖状态
		return handleGuessPromptMsg(user, m.GroupId, b)
	case messages2.MgrMessageType: // 房管私聊信息
		return handlingMgrMessage(user, b)
	case messages2.MgrHistoryType: // 获取房管私聊历史信息
		return handlingMgrHistory(user, b)
	}
	global.Log.Errorf("[Messages] unsupportted type %s", *m.Type)
	return utils.CallbackOkResp("消息type不能识别"), nil
}

func AvaChatRoomHandler(req *pb.CallbackReq, m *messages2.IncomingMessage, b []byte) (ret *pb.CallbackResp, err error) {

	user, err := GetUser(req)
	if err != nil {
		iHeader := 0
		//global.Log.Debugf("HandleIncomingMessage:%s%v", req.From_Account, err)
		if len(req.From_Account) >= 9 {
			iHeader = len(req.From_Account) - 9
		} else {
			cache.SetClientBeforeLogin(req)
			user, err = GetUser(req)
		}
		if err != nil {
			user = &chat2.ClientUser{
				Platform:   0,
				UserId:     cast.ToInt(req.From_Account),
				RoomId:     m.GroupId,
				Token:      "",
				ClientName: req.From_Account[iHeader:len(req.From_Account)], //用户走到了发言这步，给他一个id
				Avatar:     "",
				Level:      0,
				Vip:        0,
				UUID:       "",
				Props:      nil,
				Anonymouse: true,
				Role:       0,
				Permit:     0,
			}
		}
	}
	user.RoomId = cast.ToInt(req.GroupId) //应该用当前的房间号才对
	switch *m.Type {
	case messages2.LogoutMessageType:
		return handlingLogout(user)
	case messages2.SayMessageType:
		return handlingSayMessage(user, b), nil
	case messages2.LoveMessageType:
		return handlingLoveMessage(user, b)
	case messages2.GiftMessageType:
		return handlingGiftMessage(user, b)
	case messages2.PropsMessageType: //道具
		return handlingPropsMessage(user, b)

	}
	return nil, fmt.Errorf("[Messages] unsupportted type %s", *m.Type)
}
